//IrradianceVolumeGI

#ifndef IVGI
#define IVGI

#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

float3 _VolumeOrigin;
float _VolumeSize;

TEXTURE3D(_IVGI_LightMap);
SAMPLER(sampler_IVGI_LightMap);

TEXTURE2D(_IVGI_LightMap2D);
SAMPLER(sampler_IVGI_LightMap2D);

float4 SampleIVGI(float3 positionWS, float3 normalWS)
{
    float3 localPos = (positionWS - _VolumeOrigin) + normalize(normalWS);
    float3 safeSize = float3(_VolumeSize, _VolumeSize, _VolumeSize) - 1.001;
    
    // 判断是否在合法范围
    bool isInside = all(localPos >= float3(0, 0, 0)) && all(localPos <= (safeSize));

    if (!isInside)
    {
        return float4(0, 0, 0, 0);
    }

    //localPos = clamp(localPos, 0.0, safeSize); // 防止越界
    float3 uvw = localPos / safeSize;

    return SAMPLE_TEXTURE3D_LOD(_IVGI_LightMap, sampler_IVGI_LightMap, uvw, 0).rgba;
}

float4 SampleIVGI_2D(float3 positionWS, float3 normalWS)
{
    float3 localPos = (positionWS - _VolumeOrigin)  + normalize(normalWS);// 确保单位一致
    int3 coord = int3(floor(localPos + 0.5)); // 取最近的体素中心点
    // 保证不越界
    coord = clamp(coord, int3(0, 0, 0), int3(_VolumeSize - 1, _VolumeSize - 1, _VolumeSize - 1));
    
    // 展平索引
    int texWidth = _VolumeSize * _VolumeSize;
    int texHeight = _VolumeSize;
    
    float index1D = coord.x + coord.y * _VolumeSize + coord.z * _VolumeSize * _VolumeSize;
    float u = index1D % (float)texWidth;
    float v = index1D / (float)texWidth;
    
    // 最关键的一步：采样中心对齐
    float2 uv = (float2(u, v) + 0.5) / float2(texWidth, texHeight);
    
    return SAMPLE_TEXTURE2D(_IVGI_LightMap2D, sampler_IVGI_LightMap2D, uv);
    
}
#endif
